package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.Result;
import com.itheima.health.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * @Author likepei
 * @Date 2020/4/5 22:37
 * @Version v1.0
 * @Description 会员业务控制器
 */
@RestController
@Slf4j
@RequestMapping("/mobile/member")
public class MemberController {

    //依赖注入jedis
    @Autowired
    private JedisPool jedisPool;

    @Reference
    private MemberService memberService;

    /**
     * 用户登录
     * @return
     */
    @RequestMapping("/smsLogin")
    public Result smsLogin(@RequestBody Map<String, String> map){
        try {
            //1. 校验用户输入的短信验证码是否正确
            String telephone = map.get("telephone");
            String validateCode = map.get("validateCode");
            //获取redis中的验证码
            String code4Redis = jedisPool.getResource().get(telephone + RedisConst.SENDTYPE_LOGIN);

            System.out.println("telephone=" + telephone +", validateCode="+ validateCode+", code4Redis="+code4Redis);

            //2. 如果验证码错误，则登录失败
            if(code4Redis == null || code4Redis.length()==0){
                return new Result(false, "验证码过期, 请重新获取验证码");
            }
            if( !code4Redis.equals(validateCode)){
                return new Result(false, "验证码输入有误, 请重新输入");
            }

            //如果验证码成功，调用service,完成用户登录
            memberService.smsLogin(telephone);
            //登录成功, 返回成功信息
            return new Result(true, MessageConst.LOGIN_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            //登录失败, 返回失败信息
            return new Result(false, MessageConst.ACTION_FAIL);
        }
    }
}
